#include "PhysicsComponent.h"
#include "GameObject.h"
#include "VisualComponent.h"
#include "ComponentVisitor.h"


PhysicsComponent::PhysicsComponent(b2BodyType p_type, b2Vec2 p_setAsBox, b2Vec2 p_position, FixtureID p_fixtureID, int p_categoryCollisionID, int p_maskCollisionFilter, float p_density, float p_friction, float p_restitution, float p_angle)
{
			b2PolygonShape shape;
			shape.SetAsBox(p_setAsBox.x * SCALEBOX, p_setAsBox.y * SCALEBOX);
			b2FixtureDef fixtDef;
			fixtDef.shape = &shape;
			fixtDef.density = p_density;
			fixtDef.friction = p_friction;
			fixtDef.restitution = p_restitution;
			fixtDef.userData = (void*)p_fixtureID;
			fixtDef.filter.categoryBits = p_categoryCollisionID;
			fixtDef.filter.maskBits = p_maskCollisionFilter;
			m_bodyDef.angle = p_angle;
			m_bodyDef.type = p_type;
			m_bodyDef.position.Set(p_position.x * SCALEF, p_position.y * SCALEF);

			m_body = PhysicsManager::getSingleton().getWorld().CreateBody(&m_bodyDef);
			m_body->CreateFixture(&fixtDef);
}


PhysicsComponent::~PhysicsComponent()
{
	PhysicsManager::getSingleton().removeSpriteSync(m_body);
	PhysicsManager::getSingleton().getWorld().DestroyBody(m_body);
}

void PhysicsComponent::update(const GameTime& p_gameTime)
{
	getOwner()->setPosition(getPosition());
}

void PhysicsComponent::init()
{
	m_body->SetUserData(getOwner());
	IComponent* visualComponent = getOwner()->getComponent("VisualComponent");
	VisualComponent* visual = static_cast<VisualComponent*>(visualComponent);
	PhysicsManager::getSingleton().addSpriteSync(m_body, visual->getSprite());
}

void PhysicsComponent::acceptVisitor(ComponentVisitor* p_componentVisitor)
{
	p_componentVisitor->visitPhysicsComponent(this);
}